package com.cedifie.lendapp.ui.loan.act

import android.view.View
import androidx.core.view.GravityCompat
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActLoanMainBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpAct
import com.cedifie.lendapp.ui.loan.fm.CedLoanCommonFm
import com.cedifie.lendapp.ui.loan.fm.CedLoanLimitFm
import com.cedifie.lendapp.ui.loan.fm.CedLoanRepayFm
import com.cedifie.lendapp.ui.loan.impl.CedLoanMainPresenterImpl
import com.cedifie.lendapp.ui.loan.view.ICedLoanMainView
import com.cedifie.lendapp.ui.user.act.CedUserCheckPhoneNumberAct
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.ui.user.fm.CedUserFm
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.helper.ActivityStackManager
import com.lib.base.utils.helper.ForegroundBackgroundHelper
import com.lib.base.utils.helper.ForegroundBackgroundObserver
import com.lib.base.utils.log.LogHelper
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:41
 * @Annotation：贷款主页面
 */
class CedLoanMainAct: MvpAct<ICedLoanMainView, CedLoanMainPresenterImpl>(), ICedLoanMainView{

    lateinit var binding: ActLoanMainBinding

    //贷款额度
    private var limitPage: CedLoanLimitFm? = null
    //待还款
    private var repayPage: CedLoanRepayFm? = null
    //贷款 通用状态列表，包含：审核中、拒绝、放贷中、放贷中法语
    private var commonPage: CedLoanCommonFm? = null
    var eventRemark = ""

    override fun getCedRootView(): View {
        binding = ActLoanMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCedView() {
        setBackExit(true)
        setExitTips(getString(R.string.exit_tips))
        binding.parentLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)
        addMenuFragment()

        EventBus.getDefault().register(this)
        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initCedListener() {
        //个人中心
        binding.ivAvatar.setOnClickListener {
            val isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.drawerLayout.closeDrawer(GravityCompat.START,true)
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER,"$eventRemark Close")
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START,true)
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER,"$eventRemark Open")
            }
        }
        //客服
        binding.imgKefu.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER,eventRemark)
        }
    }

    override fun initCedData() {
        showCedLoading(getString(R.string.loading))
        mvpPresenter?.loadCedProcessAction()
    }

    override fun createMvpPresenter(): CedLoanMainPresenterImpl {
        return CedLoanMainPresenterImpl(getContext())
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshProcess(event: String){
        when(event){
            CedEventType.NOTICE.CED_PROCESS_REFRESH -> {//刷新流程
                mvpPresenter?.loadCedProcessAction()
            }
        }
    }

    /**
     * 添加侧边菜单
     */
    private fun addMenuFragment(){
        supportFragmentManager
            .beginTransaction()
            .add(R.id.menuLayout, CedUserFm(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 隐藏贷款所有 Page
     */
    override fun hideCedAllLoanPage() {
        limitPage?.let {
            hideContainerFragement(it)
        }
        commonPage?.let {
            hideContainerFragement(it)
        }
        repayPage?.let {
            hideContainerFragement(it)
        }
    }

    /**
     * 显示贷款额度页面
     */
    override fun showCedLoanLimitPage(isComplete: Boolean) {
        eventRemark = "LoanLimit Page"
        if (limitPage == null) {
            limitPage = CedLoanLimitFm(isComplete)
        }
        limitPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                it.isComplete = isComplete
                it.showCedStateView()
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
            }
        }
    }

    /**
     * 显示审核中、放款中、申请失败 通用页面
     */
    override fun showCedLoadCommonPage(data: JSONObject) {
        eventRemark = data.optString("eventRemark")
        if (commonPage == null) {
            commonPage = CedLoanCommonFm(data)
        }
        commonPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                commonPage?.refreshView(data)
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
            }
        }
    }

    /**
     * 显示贷款还款页面
     */
    override fun showCedLoanRepayPage() {
        eventRemark = "LoanRepayment Page"
        if (repayPage == null) {
            repayPage = CedLoanRepayFm()
        }
        repayPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                repayPage?.refreshAction()
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
            }
        }
    }

    /**
     * 校验手机号
     */
    override fun showCedCheckPhoneNumberPage() {
        //当前栈顶是 手机号校验页面 不重复跳转
        if (ActivityStackManager.isCurrentActivity(CedUserCheckPhoneNumberAct::class.java)){
            return
        }
        //是否是审核账号
        val isAdmin = SharedHelper.getCedSPBoolean(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT)
        if(isAdmin) {//审核账号，直接不走校验
            return
        }
        CedUserCheckPhoneNumberAct.start(this)
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            LogHelper.e("ced loan main background>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
            if (isForeground) {
//                mvpPresenter?.loadCedProcessAction()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}